package member

import (
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/controller/admin"
	"yunj/pkg/yunj/app/dto"
	"yunj/pkg/yunj/app/service/admin/logservice"
	"yunj/pkg/yunj/app/service/admin/memberservice"
	"yunj/pkg/yunj/core/response"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

type Login struct {
	admin.Controller
}

// 登录
func (ctrl *Login) Login(ctx *gin.Context) {
	if util.IsPost(ctx) {
		// 获取数据
		var loginData dto.AdminMemberLoginData
		ctx.ShouldBindJSON(&loginData)
		// 验证数据
		loginData.InitValidator(&loginData)
		if err := loginData.Check(); err != nil {
			response.Fail(ctx, err.Error())
			return
		}
		// 登录处理
		memberservice.Login.LoginHandle(ctx, loginData.AdminMember)
		// 记录登录成功日志
		logservice.Record(ctx, logservice.AppendArgs{
			MemberId: loginData.AdminMember.Id,
			Desc:     "登录成功",
		})
		// 响应后台入口地址
		response.Success(ctx, map[string]string{"url": global.Config.GetAppAdminEntrance()})
		return
	}
	adminEntracne := global.Config.GetAppAdminEntrance()
	data := map[string]any{
		"captchaUrl": adminEntracne + "/captcha",
		"requestUrl": adminEntracne + "/login",
	}
	ctrl.Render(ctx, "member/login", data)
}

// 退出/切换账户
func (ctrl *Login) Logout(c *gin.Context) {
	memberservice.Login.Logout(c)
	util.Redirect(c, global.Config.GetAppAdminEntrance()+"/login")
}
